package org.jeecg.modules.flower.controller;/**
 * @author gf
 * @create 2023-4-10 14:55
 */

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.chvegetable.entity.FlowerTagBook;
import org.jeecg.modules.chvegetable.service.IFlowerTagBookService;
import org.jeecg.modules.flower.entity.*;
import org.jeecg.modules.flower.service.*;
import org.jeecg.modules.flower.util.CommonUtil;
import org.jeecg.modules.flower.vo.FlowerAfSalesMainPage;
import org.jeecg.modules.flower.vo.FlowerOutorderPage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

/**
 * @author gf
 * @ClassName XsglController
 * @description: TODO
 * @datetime 2023年 04月 10日 14:55
 * @version: 1.0
 **/
@Api(tags = "销售系统接口---所有")
@RestController
@RequestMapping("/caihouApi/forXSGL")
@Slf4j
public class XsglController {
    @Autowired
    private IFlowerAfSalesMainService flowerAfSalesMainService;
    @Autowired
    private IFlowerAfSalesDetalService flowerAfSalesDetalService;


    @Autowired
    private IFlowerOutorderNewService flowerOutorderService;
    @Autowired
    private IFlowerTagBookService flowerTagBookService;


    @Autowired
    private IFlowerCostService flowerCostService;
    @Autowired
    private IFlowerPreService flowerPreService;




    @AutoLog(value = "售后单主表-添加")
    @ApiOperation(value="售后单主表-添加", notes="售后单主表-添加")
    @PostMapping(value = "/flowerAfSalesMain/add")
    public Result<?> add(@RequestBody FlowerAfSalesMainPage flowerAfSalesMainPage) {
        FlowerAfSalesMain flowerAfSalesMain = new FlowerAfSalesMain();
        BeanUtils.copyProperties(flowerAfSalesMainPage, flowerAfSalesMain);
        flowerAfSalesMainService.saveMain(flowerAfSalesMain, flowerAfSalesMainPage.getFlowerAfSalesDetalList());
        return Result.ok("添加成功！");
    }


    /**
     * 添加
     *
     * @return org.jeecg.common.api.vo.Result<?>
     * @descriptionauthor
     * @author gf
     * 2023-3-13 11:08
     * [flowerOutorderPage]
     */
    @AutoLog(value = "提交订单-添加")
    @ApiOperation(value = "提交订单-添加", notes = "提交订单-添加")
    @PostMapping(value = "/flowerOutOrder/add")
    public Result<?> add(@RequestBody FlowerOutorderPage flowerOutorderPage) throws IOException {
        FlowerOutorder flowerOutorder = new FlowerOutorder();
        BeanUtils.copyProperties(flowerOutorderPage, flowerOutorder);
        String rest = "";
        synchronized (CommonUtil.OutOrderLockKey) {
            rest = flowerOutorderService.saveMainNew(flowerOutorder, flowerOutorderPage.getFlowerOutorderinfoList());
        }
        return Result.ok("添加成功");
    }


    /**
     * 财务审核完成。。。。可出库
     *
     * @return org.jeecg.common.api.vo.Result<?>
     * @descriptionauthor
     * @author gf
     * 2023-3-13 11:07
     * [flowerOutorderPage]
     */
    @AutoLog(value = "财务审核完成")
    @ApiOperation(value = "财务审核完成", notes = "出库单表-财务审核完成")
    @GetMapping(value = "/flowerOutOrder/toHouseSure/{sealNo}")
    public Result<?> toHouseSure(@PathVariable(value = "sealNo", required = true) String sealNo) throws IOException {
        String rest = flowerOutorderService.toHouseSure(sealNo);
        return Result.ok(rest);
    }

    //销售系统结算后调用
    @ApiOperation(value = "结算-- ", notes = "结算--结算 ")
    @GetMapping(value = "/flowerOutOrder/pipBySealNo/{sealNo}")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> pipBySealNo(@PathVariable(value = "sealNo") String sealNo) throws IOException {
        String rest = flowerOutorderService.pipBySealNo(sealNo);
        return Result.ok(rest);
    }


    //冲红
    @ApiOperation(value = "冲红-- ", notes = "冲红--冲红 ")
    @PostMapping(value = "/flowerOutOrder/redOutOrderByNo/{sealNo}/{sealNoNew}")
    public Result<?> redOutOrderByNos(@RequestBody FlowerOutorderPage flowerOutorderPage, @PathVariable("sealNo") String sealNo, @PathVariable("sealNoNew") String sealNoNew) throws IOException {
        synchronized (CommonUtil.OutOrderLockKey) {
            flowerOutorderService.redOutOrderByNos(null, sealNo, sealNoNew,  flowerOutorderPage.getFlowerOutorderinfoList());
        }
        return Result.ok("冲红成功");
    }



    /**
     * 通过销售单号删除、作废、取消订单（提供给销售系统调用）
     *
     * @param sealNo
     * @return
     */
    @AutoLog(value = "通过销售单号删除、作废、取消订单（提供给销售系统调用）")
    @ApiOperation(value = "作废 ", notes = "通过销售单号删除、作废、取消订单（提供给销售系统调用）")
    @DeleteMapping(value = "/flowerOutOrder/deleteBySealNo/{sealNo}")
    public Result<?> deleteBySealNo(@PathVariable(value = "sealNo", required = true) String sealNo) throws IOException {
        log.info("销售系统调用通过销售单号删除出库单的接口，销售单号：" + sealNo);
        //根据销售单号查询出订单的id
        LambdaQueryWrapper<FlowerOutorder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FlowerOutorder::getSealNo, sealNo);
        FlowerOutorder flowerOutorder = flowerOutorderService.getOne(queryWrapper);
        if ("已结账".equals(flowerOutorder.getPeriodState())) {
            throw new RuntimeException("已结账的不允许删除！");
        }
        if (flowerOutorder.getState() == 9) {
            return Result.ok("删除成功");
        }
        if (flowerOutorder.getState() == 0) {
            throw new RuntimeException("该订单已经确认出库，不允许删除！");
        }
        if (flowerOutorder.getState() == 2) {
            throw new RuntimeException("该订单已经结算出库，不允许删除！");
        }
        synchronized (CommonUtil.OutOrderLockKey) {
            flowerOutorderService.delMain(flowerOutorder);
        }
        return Result.ok("删除成功");
    }


    @ApiOperation(value = "分组查询入库的品类等信息，用于销售系统的价格编辑", notes = "//分组查询入库的品类等信息，用于销售系统的价格编辑..-(品种编码varietyCode , 打包规格packingSpecifications ,花杆长度flowerPoleLength )")
    @GetMapping(value = "/flowerOutOrder/getFlowerVarietysAll")
    public Result<?> getFlowerVarietysAll(FlowerTagInfo flowerTagInfo,
                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                          HttpServletRequest req) {
//        QueryWrapper<FlowerTagInfo> queryWrapper = QueryGenerator.initQueryWrapper(flowerTagInfo, req.getParameterMap());
        Page<FlowerTagInfo> page = new Page<FlowerTagInfo>(pageNo, pageSize);
        QueryWrapper<FlowerTagInfo> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(flowerTagInfo.getSourceBase())) {
            queryWrapper.like("source_base", flowerTagInfo.getSourceBase());
        }
        if (StringUtils.isNotBlank(flowerTagInfo.getSourceGreenhouse())) {
            queryWrapper.eq("source_greenhouse", flowerTagInfo.getSourceGreenhouse());
        }
        if (StringUtils.isNotBlank(flowerTagInfo.getVariety())) {
            queryWrapper.like("variety", flowerTagInfo.getVariety());
        }
        if (StringUtils.isNotBlank(flowerTagInfo.getVarietyCode())) {
            queryWrapper.eq("variety_code", flowerTagInfo.getVarietyCode());
        }
        if (StringUtils.isNotBlank(flowerTagInfo.getPackingSpecifications())) {
            queryWrapper.eq("packing_specifications", flowerTagInfo.getPackingSpecifications());
        }
        if (StringUtils.isNotBlank(flowerTagInfo.getFlowerPoleLength())) {
            queryWrapper.eq("flower_pole_length", flowerTagInfo.getFlowerPoleLength());
        }
        if (StringUtils.isNotBlank(flowerTagInfo.getCost())) {
            queryWrapper.eq(" a.cost", flowerTagInfo.getCost());
        }
        IPage<FlowerTagInfo> pageList = (IPage<FlowerTagInfo>) flowerOutorderService.getFlowerVarietysALL(page, queryWrapper);
        return Result.ok(pageList);
    }


    /**
     * 根据品种编码/规格/长度---获取库存数量-
     *
     * @param varietyCode
     * @param packingSpecifications
     * @param flowerPoleLength
     * @return
     */
    @ApiOperation(value = "根据品种编码/规格/长度---获取库存数量-", notes = "根据品种编码---获取库存数量-(品种编码varietyCode , 打包规格packingSpecifications ,花杆长度flowerPoleLength )")
    @GetMapping(value = "/flowerOutOrder/getNumsByVerityCode")
    public Result<?> getNumsByVerityCode(@RequestParam(name = "sourceBase", defaultValue = "") String sourceBase,
                                         @RequestParam(name = "sourceGreenhouse", defaultValue = "") String sourceGreenhouse,
                                         @RequestParam(name = "storehouse", defaultValue = "") String storehouse,
                                         @RequestParam(name = "cost", defaultValue = "") String cost,
                                         @RequestParam(name = "varietyCode", required = true) String varietyCode,
                                         @RequestParam(name = "packingSpecifications", required = true) String packingSpecifications,
                                         @RequestParam(name = "flowerPoleLength", required = true) String flowerPoleLength) {
        QueryWrapper<FlowerTagBook> tagInfoLambdaQueryWrapper = new QueryWrapper<>();
        tagInfoLambdaQueryWrapper.select("sum(able_number) as able_number");
        if (StringUtils.isNotBlank(sourceBase)) {
            tagInfoLambdaQueryWrapper.eq("source_base", sourceBase);
        }
        if (StringUtils.isNotBlank(sourceGreenhouse)) {
            tagInfoLambdaQueryWrapper.eq("source_greenhouse", sourceGreenhouse);
        }
        if (StringUtils.isNotBlank(storehouse)) {
            tagInfoLambdaQueryWrapper.eq("storehouse", storehouse);
        }
        if (StringUtils.isNotBlank(cost)) {
            tagInfoLambdaQueryWrapper.eq("cost", cost);
        }
        tagInfoLambdaQueryWrapper.eq("variety_code", varietyCode);
        tagInfoLambdaQueryWrapper.eq("packing_specifications", packingSpecifications);
        tagInfoLambdaQueryWrapper.eq("flower_pole_length", flowerPoleLength);
        FlowerTagBook one = flowerTagBookService.getOne(tagInfoLambdaQueryWrapper);
        BigDecimal count = one.getAbleNumber();
        return Result.ok(count);
    }

    @ApiOperation(value = "弹窗查询品种编码/规格/长度..", notes = "弹窗查询品种编码/规格/长度.(品种编码varietyCode , 打包规格packingSpecifications ,花杆长度flowerPoleLength )")
    @GetMapping(value = "/flowerOutOrder/getFlowerVarietys")
    public Result<?> getFlowerVarietys(FlowerTagBook flowerTagBook,
                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                       HttpServletRequest req) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        QueryWrapper<FlowerTagBook> queryWrapper = QueryGenerator.initQueryWrapper(flowerTagBook, req.getParameterMap());
        queryWrapper.gt("able_number", 0);
        queryWrapper.inSql("storehouse", "SELECT  b.code FROM  flower_storehouse b  LEFT JOIN flower_storehouse_detail c  on b.id = c.mainid  WHERE personid = '" + sysUser.getId() + "'");
        Page<FlowerTagBook> page = new Page<FlowerTagBook>(pageNo, pageSize);
        IPage<FlowerTagBook> pageList = flowerTagBookService.page(page, queryWrapper);
        return Result.ok(pageList);
    }







    @AutoLog(value = "销售系统大屏获取-销售数据")
    @ApiOperation(value = "销售系统大屏获取-销售数据", notes = "销售系统大屏获取-销售数据")
    @GetMapping(value = "/count/getSealInfos")
    public Result<?> getSealInfos() {
        List<FlowerOutorderHZ> sealInfos = flowerCostService.getSealInfos();

        long count = flowerOutorderService.count();
        long count2 = flowerPreService.count();
        JSONObject join = new JSONObject();
        join.put("orderNum", (count + count2));
        join.put("list", sealInfos);
        return Result.ok(join);
    }

    @AutoLog(value = "销售系统大屏获取-近3个月销售数据")
    @ApiOperation(value = "销售系统大屏获取-近3个月销售数据", notes = "销售系统大屏获取-近3个月销售数据")
    @GetMapping(value = "/count/getThreeMonthSealInfos")
    public Result<?> getThreeMonthSealInfos() {
        List<FlowerOutorderHZ> sealInfos = flowerCostService.getThreeMonthSealInfos();

        QueryWrapper<FlowerOutorder> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().apply("sureouttime>DATE_SUB(CURDATE(), INTERVAL 3 MONTH)");
        long count = flowerOutorderService.count(queryWrapper1);
        QueryWrapper<FlowerPre> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.lambda().apply("stock_out_time>DATE_SUB(CURDATE(), INTERVAL 3 MONTH)");
        long count2 = flowerPreService.count(queryWrapper2);
        JSONObject join = new JSONObject();
        join.put("orderNum", (count + count2));
        join.put("list", sealInfos);
        return Result.ok(join);
    }
}